package cloud.topdaddy.admin.login.controller;

import cloud.topdaddy.admin.login.service.CaptchaService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 验证码控制器
 *
 * @author topdaddy
 * @since 2025-07-01 14:22:43
 */
@RestController
@AllArgsConstructor
@RequestMapping("/captcha")
@Tag(name = "captcha", description = "验证码")
public class CaptchaController {

    private final CaptchaService captchaService;

    /**
     * 生成验证码图片
     */
    @GetMapping("/getCaptcha")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应头，禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/png");

        // 生成验证码文本
        String captchaText = captchaService.generateCaptchaText();

        // 将验证码存入Session
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage image = captchaService.generateCaptchaImage(captchaText);

        // 输出图片到响应流
        try (OutputStream os = response.getOutputStream()) {
            ImageIO.write(image, "png", os);
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证用户输入的验证码
     */
    @GetMapping("/verifyCaptcha")
    public String verifyCaptcha(String userInput, HttpSession session) {
        String storedCaptcha = (String) session.getAttribute("captcha");

        if (storedCaptcha != null && storedCaptcha.equalsIgnoreCase(userInput)) {
            return "验证成功";
        } else {
            return "验证失败";
        }
    }

}
